/**
 * 
 */
package com.bridgetree.jubaocrm.ui.groups;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshBase.OnRefreshListener;
import com.bridgetree.jubaocrm.ui.widget.PullToRefreshListView;
import com.bridgetree.jubaocrm.util.Announcement;
import com.bridgetree.jubaocrm.util.Groups;
import com.bridgetree.jubaocrm.util.LoginError;
/**
 * GroupsAnnouncementActivity
 * </p>
 * 组内公告 2014-5-20 上午11:21:00 create
 * 
 * @since 1.0
 */
public class GroupsAnnouncementActivity extends Activity {
	private final String TAG ="GroupsAnnouncementActivity";
	private Context mContext;
	private Groups mGroups;
	private String user_id =""; 
	private String token ="";
	private ArrayList<Announcement> mAnnouncementList;
	private int scrollTopBottomma =0;
//	private int mAnnouncementListSizema =0;
	private int pageIndexma = 1;
	private GroupAnnouncementAdapter mRuAdapter2;
	private PullToRefreshListView firstcategory2 = null;
	private ListView actualListView2 = null;
	private RelativeLayout group_add_RelativeLayout = null;
	private int contactLastPos=0;
	private int scrollTopBottompr =0;
	private int pageIndexpr = 1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.group_announcement_add);
		mContext =  this;
		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");

		TextView xm_bi_tv_title =(TextView)findViewById(R.id.xm_bi_tv_title);
		if(intent.getExtras()!=null){
			mGroups = (Groups)intent.getExtras().getSerializable("groupsMain");
		}
		xm_bi_tv_title.setText("组内公告");
		
		findViewById(R.id.xm_bi_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});


		group_add_RelativeLayout = (RelativeLayout)findViewById(R.id.group_add_RelativeLayout);
		firstcategory2 = (PullToRefreshListView)findViewById(R.id.firstcategoryXM);
		firstcategory2.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				if(scrollTopBottompr == 1){
					pageIndexpr++;
					if (mGroups != null) {
						getGroupsGongGao(pageIndexpr);
					}
				}else if(scrollTopBottompr == 0){
					pageIndexpr=1;
					if (mGroups != null) {
						getGroupsGongGao(pageIndexpr);
					}
				}
			}
		});

		firstcategory2.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					contactLastPos= firstcategory2.getRefreshableView().getLastVisiblePosition();
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if (firstVisibleItem + visibleItemCount == totalItemCount) {
					scrollTopBottompr = 1;
				} else if (firstVisibleItem == 0) {
					scrollTopBottompr = 0;
				}
				System.out.println("=========" +scrollTopBottompr);
			}
		});
		actualListView2 = firstcategory2.getRefreshableView();
		
		group_add_RelativeLayout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext, GroupsAddGongGaoActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("groupsMain", mGroups);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(mGroups!=null){
			getGroupsGongGao(1);
		}
	}
	
	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}
	
	/**
	 * 获取小组公告的数据
	 * 
	 * @param pageIndex
	 */
	private void getGroupsGongGao(final int pageIndex) {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
//			http://crmsoap.woniuwo.cn/info?t=group&p=1&gid=5374743fd5ac700e4ce8f60b&user_id=cd34350bb2844077bfbd4abe5ec56f99&token=15f4b0826dc841198c30088f4a7afd90&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl
			String URL = Network.API_DOMAIN + "/info?t=group&p=" + pageIndex
			+"&gid="+mGroups.getGroup_id()+ "&user_id=" + user_id
			+ "&token=" + token + "&validation="
			+ CRMUserBaseInfo.kValication;

			final ProgressDialog progressDialog = ProgressDialog.show(this,
					"网络数据", "...Loading...");
			
			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null,
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							System.out.println("小组公告 response=" + response);
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								if (!response.isNull("is_editor_in_group")) {
									boolean enableAdd=Boolean.parseBoolean(response.getString("is_editor_in_group"));
									if(enableAdd){
										findViewById(R.id.group_add).setVisibility(View.VISIBLE);
									}
								}
								if (!response.isNull("info")) {
									String data = response.getString("info");
									if (data.equals("[]")) {
										Toast.makeText(mContext, "已经到最后了~",
												Toast.LENGTH_SHORT).show();
									} else {
										org.json.JSONArray jsonArr;
										jsonArr = response.getJSONArray("info");
										if(mAnnouncementList==null || pageIndex==1){
											mAnnouncementList = new ArrayList<Announcement>();
										}
										if (jsonArr.length() > 0) {
											for (int i = 0; i < jsonArr
											.length(); i++) {
												Announcement mAnnouncement = new Announcement();
												JSONObject jsonObj2 = jsonArr
												.getJSONObject(i);
												if (!jsonObj2.isNull("id")) {
													String id = jsonObj2
													.getString("id");
													mAnnouncement.setId(id);
												}
												if (!jsonObj2.isNull("title")) {
													String title = jsonObj2
													.getString("title");
													mAnnouncement.setTitle(title);
												}
												mAnnouncementList.add(mAnnouncement);
											}
										}
										mRuAdapter2 = new GroupAnnouncementAdapter(mContext, mAnnouncementList);
										mRuAdapter2.notifyDataSetChanged();
										actualListView2.setAdapter(mRuAdapter2);
										if (pageIndex > 1) {
											actualListView2.setSelection(contactLastPos);
										}
									}
									if (firstcategory2 != null) {
										firstcategory2.onRefreshComplete();
									}
								}
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
									.toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
											.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
												.length(); i++) {
													JSONObject jsonObj2 = jsonArr
													.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
														.getString("desc");
														mLoginError
														.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
														.getString("value");
														mLoginError
														.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (NumberFormatException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("sorry,Error");
						}
					});
			requestQueue.add(jsonObjectRequest);
		}
	}
	
}
